package cn.acmenms.utils;

import java.security.MessageDigest;

/**
 * @ClassName: StringTools
 * @Description: 字符串处理工具类
 * @author: 神奇的鸭鸭
 * @Date: 2017/12/7 9:24
 */
public class StringTools {

    /**
     * 16进制
     */
    private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

    /**
     * 判断是否非空
     * @param str 字符串
     * @return true/false
     */
    public static boolean isNotEmpty(String str){
        return null != str && !"".equals(str.trim()) && !"null".equals(str);
    }

    /**
     * 判断是否为空
     * @param str 字符串
     * @return true/false
     */
    public static boolean isEmpty(String str) {
        return (null == str) || "".equals(str.trim()) || "null".equals(str);
    }

    /**
     * 校验邮箱正则
     * @param email 邮箱
     * @return true/false
     */
    public static boolean checkEmail(String email) {
        String checkEmail = "^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+$";
        return !isEmpty(email) && email.matches(checkEmail);
    }

    /**
     * 校验用户名正则
     * @param userName 用户名
     * @return true/false
     */
    public static boolean checkUserName(String userName) {
        String checkUserName = "^[\\w\\u4e00-\\u9fa5]+$";
        return !isEmpty(userName) && userName.matches(checkUserName);
    }

    /**
     * 校验密码正则
     * @param password 密码
     * @return true/false
     */
    public static boolean checkPassword(String password) {
        String checkPassWord = "^[0-9a-zA-Z]+$";
        return !isEmpty(password) && password.matches(checkPassWord);
    }

    /**
     * MD5加密
     * @param originString 原始密码
     * @return 加密后的密码
     */
    public static String encodeByMD5(String originString) {
        if (originString != null) {
            try {
                MessageDigest md = MessageDigest.getInstance("MD5");
                byte[] results = md.digest(originString.getBytes());
                String resultString = byteArrayToHexString(results);
                return resultString.toUpperCase();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return null;
    }


    /**
     * 将字节数组转为16进制字符串
     * @param b 字节数组
     * @return 16进制字符串
     */
    private static String byteArrayToHexString(byte[] b) {
        StringBuilder resultSb = new StringBuilder();
        for (byte aB : b) {
            resultSb.append(byteToHexString(aB));
        }
        return resultSb.toString();
    }

    /**
     * 将字节转换为16进制字符串
     * @param b 字节
     * @return 十六进制字符串
     */
    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0)
            n = 256 + n;
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }
}